#include "speaker_thing.h"
#include "bsp.h"
#include <esp_log.h>

#define TAG "speaker_thing"

void speaker_set_volume(void *context, property_list_t *parameters)
{
    property_t *param = property_list_get(parameters, "volume");
    if (param)
    {
        ESP_LOGI(TAG, "volume set to %d", param->value.number);
        bsp_codec_set_volume(param->value.number);

        // 更新扬声器的属性
        property_list_t *properties = context;
        property_t *property = property_list_get(properties, "volume");
        property->value.number = param->value.number;
    }
}

void speaker_set_mute(void *context, property_list_t *parameters)
{
    property_t *param = property_list_get(parameters, "mute");
    if (param)
    {
        ESP_LOGI(TAG, "mute set to %d", param->value.boolean);
        bsp_codec_mute(param->value.boolean);

        // 更新扬声器静音属性
        property_list_t *properties = context;
        property_t *property = property_list_get(properties, "mute");
        property->value.boolean = param->value.boolean;
    }
}

thing_t *speaker_thing_create(void)
{
    // 构建扬声器属性列表：音量、静音
    property_list_t *properties = property_list_new();
    property_list_add(properties, property_create("volume", "Speaker volume", PROPERTY_VALUE_TYPE_NUMBER, (property_value_t){.number = 60}));
    property_list_add(properties, property_create("mute", "Speaker mute", PROPERTY_VALUE_TYPE_BOOL, (property_value_t){.boolean = false}));

    // 构建扬声器方法列表，调整音量、调整静音
    method_list_t *methods = method_list_new();

    // 构建SetVolume方法
    // 给Set Volume构建参数列表：音量值
    property_list_t *set_volume_parameters = property_list_new();
    property_list_add(set_volume_parameters, property_create("volume", "Volume value [0-100]", PROPERTY_VALUE_TYPE_NUMBER, (property_value_t){.number = 0}));
    // 将参数列表添加到set_volume方法
    method_list_add(methods, method_create("SetVolume", "Set speaker volume", set_volume_parameters, speaker_set_volume, properties));

    // 构建SetMute方法
    property_list_t *set_mute_parameters = property_list_new();
    property_list_add(set_mute_parameters, property_create("mute", "Mute state", PROPERTY_VALUE_TYPE_BOOL, (property_value_t){.boolean = false}));
    method_list_add(methods, method_create("SetMute", "Set speaker mute state", set_mute_parameters, speaker_set_mute, properties));

    thing_t *thing = thing_create("Speaker", "Speaker", methods, properties);
    return thing;
}